<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="title"
    :width="width"
  >
    <div style="max-height: 360px; padding: 0px; overflow: auto">
      <el-tree
        ref="treeRef"
        :check-strictly="true"
        :data="treeOptions.dataList"
        :default-expand-all="false"
        :default-expanded-keys="state.treeExpanderKeys"
        :highlight-current="true"
        lazy
        :load="lazyLoadNode"
        :props="treeOptions.props"
        :show-checkbox="multiple"
      />
    </div>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button icon="circle-check" type="primary" @click="save">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup name="DeptTreePicker">
import { queryDeptTree } from "@/api/admin/org/dept/";
import { useTree } from "@/hooks/tree";

const props = defineProps({
  title: {
    type: String,
    default: "选择组织"
  },
  width: {
    type: String,
    default: "20%"
  },
  model: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: false
  },
  expanderKeys: {
    type: Array,
    default: function () {
      return [];
    }
  }
});

const emits = defineEmits(["change"]);

const treeRef = ref(null);

const state = reactive({
  treeExpanderKeys: [].concat(props.expanderKeys),
  dialogVisible: false
});

const initTree = async () => {
  if (treeOptions.dataList && treeOptions.dataList.length > 0) {
    state.treeExpanderKeys = state.treeExpanderKeys.concat(
      treeOptions.dataList[0].id
    );
  }
};

const treeOptions = reactive({
  queryForm: { pid: "0" },
  props: {
    children: "children",
    label: "text",
    isLeaf: "leaf"
  },
  queryFunction: queryDeptTree,
  onLoaded: initTree
});

const { queryTreeData, lazyLoadNode } = useTree(treeOptions, treeRef);

const show = params => {
  Object.assign(treeOptions.queryForm, {}, params);
  queryTreeData(params);
  state.dialogVisible = true;
};

const close = () => {
  treeOptions.dataList = [];
  state.treeExpanderKeys = [];
  state.dialogVisible = false;
};

const save = () => {
  let nodes;
  if (props.multiple) {
    nodes = treeRef.value.getCheckedNodes();
  } else {
    nodes = treeRef.value.getCurrentNode();
  }
  emits("change", nodes);
  close();
};

defineExpose({
  show,
  close,
  save
});
</script>
<style lang="scss" scoped></style>
